package com.book.bookprojectapplication.login.activity;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.book.bookprojectapplication.R;
import com.tistory.whdghks913.croutonhelper.CroutonHelper;

import de.keyboardsurfer.android.widget.crouton.Style;

public class RegisterSecondActivity extends Activity {

	CroutonHelper mHelper;
	Button backregisterfirstBtn, emailcodeBtn, emailconfirmBtn, nextBtn;
	EditText emailText, emailconfirmText, extraemailText, passwordText,
			confirmpasswordText;

	TextView textView2;

	String getcode; // 인증 코드 값
	String totalcode;

	HttpResponse response;
	String results;
	String memail1;
	String memail;
	String memail2;
	String mpassword;

	JSONObject jArray;

	String url = "http://192.168.123.182:8090/test/csjemailcheck.do";
	private String getJsonData;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		mHelper = new CroutonHelper(this);
		mHelper.setDuration(1000);

		setContentView(R.layout.registersecond);
		emailText = (EditText) findViewById(R.id.emailText);
		emailconfirmText = (EditText) findViewById(R.id.emailconfirmText);
		extraemailText = (EditText) findViewById(R.id.extraemailText);
		passwordText = (EditText) findViewById(R.id.passwordText);
		confirmpasswordText = (EditText) findViewById(R.id.confirmpasswordText);

		backregisterfirstBtn = (Button) findViewById(R.id.backregisterfirstBtn);

		backregisterfirstBtn.setOnClickListener(new Button.OnClickListener() {

			public void onClick(View v) {

				Intent myIntent = new Intent(getApplicationContext(),
						RegisterFirstActivity.class);

				startActivity(myIntent);

			}

		});

		emailcodeBtn = (Button) findViewById(R.id.emailcodeBtn);

		emailcodeBtn.setOnClickListener(new Button.OnClickListener() {

			public void onClick(View v) {

				memail1 = "?memail1=" + emailText.getText().toString();
				System.out.println(memail1);

				new DownloadJSON().execute(url);

			}

		});

		nextBtn = (Button) findViewById(R.id.nextBtn);
		nextBtn.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {

				final String email = extraemailText.getText().toString();
				final String password = passwordText.getText().toString();

				if (email.equals("")) {
					mHelper.setStyle(Style.ALERT);
					mHelper.setText("예비 이메일을 넣어주세요");
					mHelper.show();
					return;

				} else if (!isValidEmail(email)) {
					mHelper.setStyle(Style.ALERT);
					mHelper.setText("틀린이메일형식입니다.");
					mHelper.show();

				}

				if (password.trim().length() <= 0) {
					mHelper.setStyle(Style.ALERT);
					mHelper.setText("비밀번호를 넣어주세요");
					mHelper.show();
					return;
				} else if (!isValidPassword(password)) {
					mHelper.setStyle(Style.ALERT);
					mHelper.setText("영문, 숫자 혼용해서 6~20자 이내로 비밀번호를 만들어주세요");
					mHelper.show();
					return;
				}

				if (confirmpasswordText.getText().toString().equals("")) {
					mHelper.setStyle(Style.ALERT);
					mHelper.setText("비밀번호를 넣어주세요");
					mHelper.show();
					return;
				} else if (!(passwordText.getText().toString()
						.equals(confirmpasswordText.getText().toString()))) {
					mHelper.setStyle(Style.ALERT);
					mHelper.setText("비밀번호가 다릅니다.");
					mHelper.show();
					return;

				}
				if (emailconfirmText.getText().toString().equals("")) {
					mHelper.setStyle(Style.ALERT);
					mHelper.setText("인증을 받으세요");
					mHelper.show();
					return;
				}
				{

					// mHelper.setStyle(Style.ALERT);
					// mHelper.setText("dfsdfd");
					// mHelper.show();

					Intent myIntent = new Intent(getApplicationContext(),
							RegisterThirdActivity.class);

					memail = emailText.getText().toString();
					memail2 = extraemailText.getText().toString();
					mpassword = passwordText.getText().toString();

					myIntent.putExtra("memail1", memail);
					myIntent.putExtra("memail2", memail2);
					myIntent.putExtra("mpassword", mpassword);

					startActivity(myIntent);

					System.out
							.println("================================================");
					System.out.println(memail);
					System.out.println(memail2);
					System.out.println(mpassword);

				}
			}

			// validating email id
			private boolean isValidEmail(String email) {
				String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
						+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

				Pattern pattern = Pattern.compile(EMAIL_PATTERN);

				Matcher matcher = pattern.matcher(email);

				return matcher.matches();

			}

			// validating password
			// 영문, 숫자 혼용해서 6~20자 이내
			private boolean isValidPassword(String password) {
				// String PASSWORD_PATTERN =
				// "^.*(?=.{6,20})(?=.*[0-9])(?=.*[a-zA-Z]).*$";
				String PASSWORD_PATTERN = "^(?=.*[a-zA-Z])(?=.*[!@#$%^*+=-]|.*[0-9]).{6,24}$";

				Pattern pattern = Pattern.compile(PASSWORD_PATTERN);
				Matcher matcher = pattern.matcher(password);

				return matcher.matches();

			}
		});

		emailconfirmBtn = (Button) findViewById(R.id.emailconfirmBtn);
		textView2 = (TextView) findViewById(R.id.textView2);
		emailconfirmBtn.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View v) {

				final String codeNumber = emailconfirmText.getText().toString();
				getcode = emailconfirmText.getText().toString();

				if (emailconfirmText.getText().toString().equals("")) {
					mHelper.setStyle(Style.ALERT);
					mHelper.setText("인증번호를 넣어주세요");
					mHelper.show();
				} else if (!getcode.equals(totalcode)) {
					mHelper.setStyle(Style.ALERT);
					mHelper.setText("인증번호를 확인해주세요");
					mHelper.show();
					emailconfirmText.setText("");
				} else if (getcode.equals(totalcode)) {
					mHelper.setStyle(Style.ALERT);
					mHelper.setText("인증성공!!");
					mHelper.show();
					emailconfirmText.setVisibility(View.GONE);
					emailconfirmBtn.setVisibility(View.GONE);
					textView2.setVisibility(View.GONE);
					emailText.setKeyListener(null);
				}
			}

		});

	}

	/*
	 * 이메일 중복 체크
	 */
	private class DownloadJSON extends AsyncTask<String, Void, Void> {

		@Override
		protected Void doInBackground(String... urls) {

			System.out.println("doInBackground ()");
			InputStream is = null;
			results = "";
			String idcheck = memail1;
			System.out.println("idcheck is " + idcheck);

			// Download JSON data from URL
			try {
				HttpClient httpclient = new DefaultHttpClient();
				HttpPost httppost = new HttpPost(urls[0] + idcheck);
				response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();

				// Convert response to string

				BufferedReader reader = new BufferedReader(
						new InputStreamReader(is, "utf-8"), 8);
				StringBuilder sb = new StringBuilder();
				String line = null;
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();
				results = sb.toString();
				System.out.println("result 값 : " + results);
				jArray = new JSONObject(results);

				JSONArray resarray = jArray.getJSONArray("checkresult");
				for (int i = 0; i < resarray.length(); i++) {
					jArray = resarray.getJSONObject(i);
					getJsonData = jArray.getString("res");
				}

				System.out.println("getJsonData is : " + getJsonData);

			} catch (Exception e) {
				Log.e("log_tag", "Error converting result " + e.toString());
			}

			return null;

		}

		@Override
		protected void onPostExecute(Void args) {
			createcode();

			mHelper = new CroutonHelper(RegisterSecondActivity.this);
			mHelper.setDuration(1000);

			System.out.println("onPosetExecute ()");
			System.out.println("total email code is : " + totalcode);

			final String email = emailText.getText().toString();

			emailcodeBtn = (Button) findViewById(R.id.emailcodeBtn);

			if (emailText.getText().toString().equals("")) {
				mHelper.setStyle(Style.ALERT);
				mHelper.setText("이메일을 넣어주세요");
				mHelper.show();
			} else if (getJsonData.equals("no")) {
				mHelper.setStyle(Style.ALERT);
				mHelper.setText("이미 등록된 이메일 입니다.");
				mHelper.show();
			} else if (!isValidEmail(email)) {
				mHelper.setStyle(Style.ALERT);
				mHelper.setText("틀린이메일형식입니다.");
				mHelper.show();
			} else {

				mHelper.setText(emailText.getText()
						+ "으로 인증코드가 발송되었습니다. 인증코드를 확인해주세요");
				mHelper.show();
				Log.i("SendMailActivity", "Send Button Clicked.");

				String fromEmail = "chaesj818@gmail.com";
				String fromPassword = "cj000909";
				String toEmails = emailText.getText().toString();
				List<String> toEmailList = Arrays.asList(toEmails
						.split("\\s*,\\s*"));
				Log.i("SendMailActivity", "To List: " + toEmailList);
				String emailSubject = "[책,보다너]회원가입 인증 번호";

				String emailBody = "인증번호는  : " + " " + totalcode + " ";

				new SendMailTask(RegisterSecondActivity.this).execute(
						fromEmail, fromPassword, toEmailList, emailSubject,
						emailBody);

			}
			System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!");
		}

		// validating email id
		private boolean isValidEmail(String email) {
			String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
					+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

			Pattern pattern = Pattern.compile(EMAIL_PATTERN);
			Matcher matcher = pattern.matcher(email);
			return matcher.matches();
		}

		/*
		 * 인증코드 생성
		 */
		public void createcode() {
			double num = Math.floor(Math.random() * 1000000) + 100000;
			String code = String.valueOf(num).substring(0, 6);
			totalcode = code;
		}

	}
}
